﻿using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;

namespace POC.Reports.Formatter
{

    public static class SerializerFormaterExtn
    {

        #region Serializable
        public static byte[] ToByteArray(this object message)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter( );
                formatter.Serialize(stream, message);
                return stream.ToArray();
            }
        }

        public static string ToXml<T>(this T message)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T), new Type[] { typeof(TableEntity) });
                formatter.Serialize(stream, message);
                return UTF8Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        public static T FromXml<T>(this string buffer)
        {
            using (MemoryStream stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(buffer)))
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T), new Type[] { typeof(TableEntity) });
                object o = formatter.Deserialize(stream);
                return (T)o;
            }
        }
        public static T ToEntity<T>(this byte[] buffer)
        {
            using (MemoryStream stream = new MemoryStream(buffer))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                object o = formatter.Deserialize(stream);
                return (T)o;
            }
        }
        #endregion
    }
}
